import React from 'react';
import { Link } from 'react-router';
import { Breadcrumb, Row, Col, Input, DatePicker, Select, Button, Table, Modal, Pagination, message, Popconfirm, Form } from 'antd';
import moment from 'moment';
import $ from 'jquery';
import Config from '../../common/config';

const FormItem = Form.Item;
const Textarea = Input.TextArea;
const config = new Config();

class diseaseManage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      diseaseData: [
        {
          id: 1,//id
          title: '感冒', //疾病名称
          behavior: '发烧', //症状表现
          reason: '着凉',//病症缘由
          complex: '头痛',//并发症
          status: '已发布', //状态
          page: 1, //页码
        }
      ], //病症表格数据
      title: '', //疾病名称
      behavior: '',//症状表现
      status: null,  //0未发布 1已发布 all全部
      page: 1,
      pageSize: 10,
      total: 5,
      addModal: false,//添加模态框
      isNew: false,//是否是新增
      changeId: '',//是否
    }
    this.InputSearch = this.InputSearch.bind(this)
  }

  componentDidMount() {
    this.initData()
  }

  // 获取初始数据
  initData() {
    $.ajax({
      url: `${config.healthAftercare}/healthplatform/disease`,
      type: 'get',
      data: {
        pagesize: this.state.pageSize,
        pageindex: this.state.page,
        title: this.state.title,
        behavior: this.state.behavior,
        status: this.state.status
      },
      headers: {
        'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
      },
      success: res => {
        console.log(res)
        if (res.code == 200) {
          this.setState({
            diseaseData: res.data.rows,
            total: res.data.count
          })
        }
      }
    })
  }
  //输入搜索条件
  InputSearch(tip, e) {
    let val = e.target.value
    console.log(tip, e.target.value)
    if (tip === 0) {
      this.setState({
        title: val
      })
    } else if (tip === 1) {
      this.setState({
        behavior: val
      })
    } else {

    }
  }
  // 选择发布状态
  selectChange(e) {
    console.log(e)
    this.setState({
      status: e
    })
  }

  // 搜索/清空
  filterOrders(key) {
    if (key) {
      // 搜索
      this.setState({
        page: 1
      }, () => {
        this.initData();
      });
    } else {
      // 清空
      this.setState({
        page: 1,
        title: '',
        behavior: '',
        status: null,
      }, () => {
        this.initData();
      });
    }
  }

  // 切换分页
  onChangePage(page) {
    this.setState({
      page
    }, () => {
      this.initData();
    });
  }

  // 显示模态框
  showModal(value) {
    console.log('是否是编辑', value)
    if (value) {//编辑
      this.setState({
        isNew: false,
        addModal: true,
        changeId: value.id
      }, () => {
        this.props.form.setFieldsValue({
          disease_title: value.disease_title,
          disease_reason: value.disease_reason,
          disease_complex: value.disease_complex,
          disease_status: value.disease_status,
          disease_behavior: value.disease_behavior
        })
      })
    } else {
      this.setState({
        isNew: true,
        addModal: true
      })
    }

  }

  // 删除
  deletedise(record) {
    console.log('删除', record)
    $.ajax({
      url: `${config.healthAftercare}/healthplatform/disease`,
      method: 'delete',
      headers: {
        'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
      },
      data: {
        id: record.id
      },
      success: res => {
        console.log(res)
        if (res.code === 200) {
          message.success(res.mes)
          this.initData()
        } else {
          message.error(res.mes)
        }
      }

    })
  }
  // 发布和下架
  publish(record, status) {
    console.log('发布', record, status)
    $.ajax({
      url: `${config.healthAftercare}/healthplatform/disease`,
      method: 'put',
      headers: {
        'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
      },
      data: {
        id: record.id,
        status
      },
      success: res => {
        console.log(res)
        if (res.code === 200) {
          message.success(res.mes)
          this.initData()
        } else {
          message.error(res.mes)
        }
      }
    })
  }


  // 表格
  getColumns() {
    return [{
      title: '序号',
      width: '5%',
      dataIndex: 'id'
    }, {
      title: '疾病名称',
      width: '10%',
      dataIndex: 'disease_title'
    }, {
      title: '症状表现',
      width: '10%',
      dataIndex: 'disease_behavior'
    }, {
      title: '病症原由',
      width: '10%',
      dataIndex: 'disease_reason'
    }, {
      title: '并发症',
      width: '15%',
      dataIndex: 'disease_complex'
    }, {
      title: '状态',
      width: '15%',
      dataIndex: 'disease_status',
      render: (text, record) => {
        return <p>{record.disease_status === 0 ? '未发布' : '已发布'}</p>
      }
    }, {
      title: '操作',
      width: '20%',
      render: (text, record) => {
        return <div>
          <div style={record.disease_status === 0 ? { display: "inline" } : { display: "none" }}>
            <Button type="primary" onClick={this.showModal.bind(this, record)} >编辑</Button>&nbsp;&nbsp;&nbsp;&nbsp;
            <Button type="primary" onClick={this.publish.bind(this, record, 1)} >发布</Button>&nbsp;&nbsp;&nbsp;&nbsp;
            <Popconfirm title="您确定要删除么？" okText="是" cancelText="否" onConfirm={this.deletedise.bind(this, record)}>
              <Button type="danger">删除</Button>
            </Popconfirm>
          </div>
          <div style={record.disease_status === 1 ? { display: "inline" } : { display: "none" }}>
            <Button type="primary" onClick={this.publish.bind(this, record, 0)} >下架</Button>
          </div>
        </div>
      }
    }]
  }

  // 保存
  save(e) {
    console.log(e)
    this.props.form.validateFields((err, values) => {
      console.log(err, values, '提交')
      if (!err) {
        console.log('格式正确')
        let data = {
          title: values.disease_title,
          behavior: values.disease_behavior,
          reason: values.disease_reason,
          complex: values.disease_complex,
        }
        let method = ''
        if (this.state.isNew === false) {
          data.id = this.state.changeId
          method = 'put'
        } else {
          method = 'post'
        }
        $.ajax({
          url: `${config.healthAftercare}/healthplatform/disease`,
          method,
          data,
          headers: {
            'Authorization': 'Bearer ' + sessionStorage.getItem('token'),
          },
          success: res => {
            console.log(res)
            if (res.code === 200) {
              message.success(res.mes)
              this.setState({
                addModal: false
              })
              this.props.form.resetFields();
              this.initData()
            }else{
              message.error(res.mes)
            }
          }
        })
      }
    })
  }
  //取消，关闭对话框
  handleCancel() {
    this.props.form.resetFields();
    this.setState({
      addModal: false,
    });
  }



  render() {
    const columns = this.getColumns();
    const formItemLayout = { labelCol: { span: 4 }, wrapperCol: { span: 20 } };
    const { getFieldDecorator } = this.props.form;
    return (
      <div className='goods-label clerafix'>
        < Breadcrumb separator=">" >
          <Breadcrumb.Item>健康调养</Breadcrumb.Item>
          <Breadcrumb.Item>病症管理</Breadcrumb.Item>
        </Breadcrumb >
        <div style={{ marginTop: '20px' }}>
          <div className="member-content-Search" style={{ marginBottom: 20 }}>

            <Row type="flex" justify="space-between">
              <Col span={5}>
                <Input addonBefore='疾病名称' placeholder="请输入" value={this.state.title}  onChange={this.InputSearch.bind(this, 0)} />
              </Col>
              <Col span={5}>
                <Input addonBefore='症状表现' placeholder="请输入" value={this.state.behavior} onChange={this.InputSearch.bind(this, 1)} />
              </Col>
              <Col span={5}>
                {/* <Input addonBefore='审核状态' placeholder="请输入"  onChange={this.InputSearch.bind(this,2)} /> */}
                <span>审核状态:&nbsp;&nbsp;</span><Select value={this.state.status} onChange={this.selectChange.bind(this)} style={{ width: '120px', height: '40px' }}>
                  <Option value="all">全部</Option>
                  <Option value="0">未发布</Option>
                  <Option value="1" >已发布</Option>
                </Select>
              </Col>
              <Col span={5}>
                <Button className='ant-btn-primary' icon='search' onClick={this.filterOrders.bind(this, 1)}>搜索</Button>
                <Button className='ant-btn-primary' icon='sync' onClick={this.filterOrders.bind(this, 0)}>重置</Button>
              </Col>
            </Row>
          </div>

        </div>
        <div>
          <Button className='ant-btn-primary' onClick={this.showModal.bind(this, false)}>新增疾病</Button>
        </div>
        <div style={{ marginTop: '20px' }}>
          <Table columns={columns} dataSource={this.state.diseaseData} pagination={false} bordered />
        </div>
        <div className='goods-label-let clearfix'>
          <div className="floor-ppagi">
            {
              this.state.total == 0 ?
                <p className="floor-ppagip">
                  共{this.state.total}条记录
              </p> :
                <p className="floor-ppagip">
                  当前显示
                {this.state.pageSize * (this.state.page - 1) + 1}—
                {this.state.pageSize * this.state.page < this.state.total ? this.state.pageSize * this.state.page : this.state.total}条记录，
                共{this.state.total}条记录
              </p>
            }
            <Pagination current={this.state.page} total={this.state.total || 1} defaultPageSize={this.state.pageSize} onChange={this.onChangePage.bind(this)} />
          </div>
        </div>
        <Modal
          title={this.state.isNew === true ? '新增疾病' : '编辑'}
          visible={this.state.addModal}
          okText='提交'
          cancelText='取消'
          onCancel={this.handleCancel.bind(this)}
          onOk={this.save.bind(this)}
        >
          <Form >
            <FormItem
              label='疾病名称'
              {...formItemLayout}
            >
              {getFieldDecorator('disease_title', {
                rules: [{
                  required: true, message: '限15字内（必填项）',
                  max: 15, message: '限15字内',
                }]
              })(
                <Input type='title' placeholder='请填写疾病名称' />
              )}

            </FormItem>

            <FormItem
              label='病症表现'
              {...formItemLayout}
            >
              {getFieldDecorator('disease_behavior', {
                rules: [{
                  required: true, message: '请填写病症表现',
                  max: 500, message: '限500字内',
                }]
              })(
                <Textarea type='title' placeholder='病症表现' style={{ height: '100px' }} />
              )}

            </FormItem>
            <FormItem
              label='病症原由'
              {...formItemLayout}
            >
              {getFieldDecorator('disease_reason', {
                rules: [{
                  required: true, message: '请填写病症原由',
                  max: 1000, message: '限1000字内',
                }]
              })(
                <Textarea type='title' placeholder='限1000字内（必填项）' style={{ height: '100px' }} />
              )}

            </FormItem>
            <FormItem
              label='并发症'
              {...formItemLayout}
            >
              {getFieldDecorator('disease_complex', {
                rules: [{
                  max: 500, message: '限500字内',
                }]
              })(
                <Textarea type='title' placeholder='限500字内（非必填项）' style={{ height: '100px' }} />
              )}

            </FormItem>
          </Form>
        </Modal>
      </div>

    )
  }
}


export default Form.create()(diseaseManage);